#coding:utf8
'''
mapping scripts
完成API文档到TOPAPI数据库表结构的映射操作，在当前目录下生成TOPAPI_DDL.SQL文件
'''
import re
import os
from TopAPI.lib import getConn
from TopAPI.config import mapping,field_type_mapping

ddl='''
DROP TABLE IF EXISTS `$TB_NAME$`;
CREATE TABLE `$TB_NAME$`(
$FIELDS$,
POPULATION_TSMP TIMESTAMP
)ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='$COMMENT$';
'''

def generate_field_type(fieldType):
	if field_type_mapping.has_key(fieldType):
		fd_type=field_type_mapping[fieldType]
	elif fieldType.endswith(' []'):
		fd_type='VARCHAR(300)'
	else:
		fd_type='VARCHAR(50)'
	return fd_type

def ddl_template(tbName,fileds,index=None,comment=''):
	'''
	DDL tempalte
	param tnName : 
	param fields : [FIELD,TYPE,DESC]
	'''
	fields_ddl_list=list()
	for fd in fileds:
		#fd_comment=fd[2].replace('\'','"')#.encode('utf-8')
		#fields_ddl_list.append("    `%s` %s COMMENT '%s'"%(fd[0],generate_field_type(fd[1]),fd_comment))
		fields_ddl_list.append("    `%s` %s"%(fd[0],generate_field_type(fd[1])))
	fields_ddl_list=',\n'.join(fields_ddl_list)
	return ddl.replace('$TB_NAME$',tbName)\
	.replace('$FIELDS$',fields_ddl_list)\
	.replace('$COMMENT$',comment)

def produceTopAPIDB():
	'''
	根据TAOBAOAPI数据库和mapping更新TOPAPI中的表
	'''
	#step 1:创建TOPAPI数据库的DDL文件夹
	ddl_dir=os.path.join(os.getcwd())
	#if not os.path.exists(ddl_dir):os.mkdir(ddl_dir)
	#step 2:对mapping里面设计到的表，生成其DDL语句
	db=getConn('TAOBAOAPI')
	f=open(os.path.join(ddl_dir,'TOPAPI_DDL.SQL'),'w')
	for tbName in mapping.keys():
		fields=list()
		db.query("SELECT FIELD,TYPE FROM apidatastruct WHERE CLASS='%s' ORDER BY FINDEX"%tbName)
		r=db.store_result()
		for i in range(r.num_rows()):
			fields.append(r.fetch_row()[0])
		#如果主键不在表内，则在前面插入相应的外键
		for t in mapping[tbName]:
			if t['type']=='self':
				pass
			elif t['type']=='session':
				fields.insert(0,(t['pk'],'String'))
			else:
				parent_tb=re.findall(r'\S+',t['type'])[0]
				db.query("SELECT FIELD,TYPE FROM apidatastruct WHERE CLASS='%s' AND FIELD='%s'"%(parent_tb,t['pk']))
				r=db.store_result()
				for i in range(r.num_rows()):
					fields.insert(0,r.fetch_row()[0])
		ddl=ddl_template(tbName,fields)
		f.write(ddl)
	f.close()
	db.close()
	return

def main():
	produceTopAPIDB()
	pass

if __name__ == '__main__':
	main()